package com.qf.sl.youshare.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import com.qf.sl.youshare.R;
import com.qf.sl.youshare.adapters.SheJiaoCircleAdapter;
import com.qf.sl.youshare.model.Circle;
import com.qf.sl.youshare.tasks.ShareCircleTask;
import com.qf.sl.youshare.tasks.TaskProcessor;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;

/**
 * Created by IDEA
 * User : SL
 * on  2015/2/17.
 * 22:20
 */
public class SheJiaoCircleFragment extends Fragment implements AdapterView.OnItemClickListener, TaskProcessor {

    private boolean hasFirstLoad = false;
    private LinkedList<Circle> circles;
    private SheJiaoCircleAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View ret = inflater.inflate(R.layout.fragment_shejiao_circle, container, false);

        GridView gridView = (GridView) ret.findViewById(R.id.shejiao_circle_gridview);

        if (gridView != null) {
            circles = new LinkedList<Circle>();
            adapter = new SheJiaoCircleAdapter(getActivity(), circles);

            gridView.setAdapter(adapter);

            gridView.setOnItemClickListener(this);
        }

        if (!hasFirstLoad){
            ShareCircleTask task = new ShareCircleTask(this);
            task.execute();
        }

        return ret;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void processResult(JSONObject jsonObject) {
        try {
            int code = jsonObject.getInt("code");
            if (code == 1){
                JSONObject msg = jsonObject.getJSONObject("msg");
                JSONArray dataArray = msg.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {
                    JSONObject dataObject = dataArray.getJSONObject(i);
                    Circle circle = new Circle();
                    circle.parseJSON(dataObject);

                    circles.add(circle);
                }
                adapter.notifyDataSetChanged();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        hasFirstLoad = true;
    }
}